<template>
  <div class="clearfix">
    <a-upload
        :file-list="fileList"
        :remove="handleRemove"
        :before-upload="beforeUpload">
      <a-button>
        <a-icon type="upload"/>
        选择文件
      </a-button>
    </a-upload>
    <div>
      <span>预览文件：</span><br/>
      <img v-for="(url) in currentUrls" class="review" v-if="currentUrls.length > 0" :src="url" alt="文件">
    </div>
    <a-button
        type="primary"
        :disabled="fileList.length === 0"
        :loading="uploading"
        style="margin-top: 16px"
        @click="handleUpload"
    >
      {{ uploading ? 'Uploading' : '开始上传' }}
    </a-button>
  </div>
</template>
<script>
import {uploadFiles} from '@/services/document'

export default {
  props: {
    placeholder: {
      type: String,
      required: true
    },
    acceptTypes: {
      type: Array,
      required: true
    },
    value: {
      type: Array,
      required: true
    },
    maxSize: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      currentUrls: this.value,
      fileList: [],
      uploading: false,
    };
  },
  methods: {
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      console.log(file);
      const currentFileCount = this.fileList.length;
      const newFileCount = currentFileCount + 1;
      if (newFileCount > this.maxSize) {
        this.$message.warning(`最多只能上传${this.maxSize}个文件`);
        return false;
      }
      const fileName = file.name.toLowerCase();
      const isAllowedType = this.acceptTypes.some(ext => fileName.endsWith(ext))
      if (!isAllowedType) {
        this.$message.error('只能上传固定格式的文件！');
        return false;
      }
      this.fileList = [...this.fileList, file];
      return false;
    },
    handleUpload() {
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('files', file);
      })
      console.log('$f(handleUpload)=>', formData.get('files'));
      this.uploading = true;
      uploadFiles(formData).then(res => {
        if (res.data.code === 200) {
          this.uploading = false;
          this.$message.success('上传成功!');
          this.currentUrl = res.data.data.url;
          this.$emit('input', res.data.data.url);
        } else {
          this.uploading = false;
          this.$message.error(res.data.message);
        }
      })
    },
  },
};
</script>

<style scoped lang="less">
.review {
  width: 100px;
  height: 100px;
  object-fit: cover
}
</style>
